//
//  TCPSocket.cpp
//  MultiPlayer
//
//  Created by 星落之尘 on 2020/6/9.
//  Copyright © 2020 Tan. All rights reserved.
//

#include "TCPSocket.h"

#include "RoboCatPch.h"
int TCPSocket::Connect(const SocketAddress &inAddress)
{
    int err = connect(mSocket, &inAddress.mSockAddr, inAddress.GetSize());
    if (err < 0) {
        SocketUtil::ReportError( "TCPSocket::Connect" );
        return ~SocketUtil::GetLastError();
    }
    return NO_ERROR;
}

int TCPSocket::Listen(int inBackLog)
{
    int err = listen(mSocket, inBackLog);
    if (err < 0)
    {
        SocketUtil::ReportError("TCPSocket::Listener");
        return -SocketUtil::GetLastError();
    }
    
    return NO_ERROR;
}

int TCPSocket::Bind(const SocketAddress& inBindAddrss)
{
    int error = bind(mSocket, &inBindAddrss.mSockAddr, inBindAddrss.GetSize());
    if (error != 0)
    {
        SocketUtil::ReportError("TCPSocket::Bind");
        return SocketUtil::GetLastError();
    }
    return NO_ERROR;
}

TCPSocketPtr TCPSocket::Accept(SocketAddress &inFromAddress)
{
    socklen_t lenght = inFromAddress.GetSize();
    SOCKET newSocket = accept(mSocket, &inFromAddress.mSockAddr, &lenght);
    
    if (newSocket != INVALID_SOCKET) {
        return TCPSocketPtr( new TCPSocket( newSocket ) );
    }
    else
    {
        SocketUtil::ReportError("TCPSocket::Accept");
        return nullptr;
    }
}

int32_t TCPSocket::Send(const void* inData, size_t inLen)
{
    int bytesSendCount = send(mSocket, static_cast<const char*>(inData), inLen, 0 );
    if (bytesSendCount < 0) {
        SocketUtil::ReportError("TCPSocket::Send");
        return -SocketUtil::GetLastError();
    }
    
    return bytesSendCount;
}


int32_t TCPSocket::Receive(void* inData, size_t inLen)
{
    int bytesReceivedCount = recv(mSocket, static_cast<char*>(inData), inLen, 0);
    if (bytesReceivedCount < 0) {
        SocketUtil::ReportError("TCPSocket::Receive");
        return -SocketUtil::GetLastError();
    }
    return bytesReceivedCount;
}



TCPSocket::~TCPSocket()
{
#if _WIN32
    closesocket(mSocket);
#else
    close(mSocket);
#endif
}
